package com.example.weather_plus.ui.weatherforecast.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.weather_plus.data.model.CityInfo;
import com.example.weather_plus.data.model.WeatherInfo;
import com.example.weather_plus.data.repository.GeoRepository;


public class GeoViewModel extends AndroidViewModel {
    private final MutableLiveData<CityInfo> weatherText = new MutableLiveData<>();
    private final GeoRepository repository;

    private String location = "120.0,30.0";
    private final String apiKey = "7c55e04213a340cc87f79b837edfc53b";
    private final MutableLiveData<String> locationLiveData = new MutableLiveData<>();

    public GeoViewModel(@NonNull Application application) {

        super(application);
        repository = new GeoRepository();

        locationLiveData.observeForever(newLocation -> {
            if (!TextUtils.isEmpty(newLocation)) {
                location = newLocation; // 更新location属性
                fetchGeoInfo();
            }
        });
    }

    public void fetchGeoInfo() {
        LiveData<CityInfo> geo = repository.fetchCityInfo(location, apiKey);

        geo.observeForever(info -> {
            if (info != null) {
                weatherText.postValue(info);
            } else {
                Log.e("GGGG", "Received null GGGG");
            }
        });
    }


    private String processWeatherInfo(WeatherInfo weatherInfo) {
        // 根据需要处理WeatherInfo对象，提取所需信息转换为String
        // 示例：返回城市名称
        return weatherInfo.getCode();
    }

    public LiveData<CityInfo> getCityInfo() {
        fetchGeoInfo();
        return weatherText;
    }

    public void setLocation(String set) {
        locationLiveData.postValue(set); // 使用postValue更新LiveData，确保在主线程上操作
    }

}